import { Component, OnInit } from '@angular/core';
import {PublicService} from '../../services/public.service';
import {Message, TreeNode} from 'primeng/primeng';
import {FormObjModel} from '../formObj.model';
import {RequestForServiceService} from '../request-for-service.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {EventBusService} from '../../services/event-bus.service';
import {PUblicMethod} from '../../services/PUblicMethod';

@Component({
  selector: 'app-assign-service',
  templateUrl: './assign-service.component.html',
  styleUrls: ['./assign-service.component.scss']
})
export class AssignServiceComponent implements OnInit {
    display: boolean = false;
    filesTree4: TreeNode[] = [];
    selected: Array<any> = [];
    formObj: FormObjModel;
    options: Object = {
        'departments': []
    };
    message: Message[] = [];               // 交互提示弹出框
    myForm: FormGroup;

    constructor(   private publicService: PublicService,
                   private rfsService: RequestForServiceService,
                   private router: Router,
                   private eventBusService: EventBusService,
                   private activatedRouter: ActivatedRoute,
                   private fb: FormBuilder) { }

    ngOnInit() {
        this.fb = new FormBuilder();
        this.formObj = new FormObjModel();
        this.createForm();
        this.getDepPerson();
        this.formObj.sid = this.activatedRouter.snapshot.paramMap.get('id');
        this.formObj.status = this.activatedRouter.snapshot.paramMap.get('status');
        this.rfsService.getFlowChart(this.formObj.status).subscribe(res => {
            this.eventBusService.rfs.next(res);
        });
    }
    goBack() {
        this.router.navigate(['../serviceOverview'], {relativeTo: this.activatedRouter});
    }
    createForm() {
        this.myForm = this.fb.group({
            'department': ''
        });
    }
    showTreeDialog() {
        this.display = true;
        this.publicService.getDepartmentDatas().subscribe(res => {
            this.filesTree4 = res;
        });
    }
    clearTreeDialog() {
        this.formObj.acceptor = '';
        this.formObj.acceptor_org = '';
        this.formObj.acceptor_org_oid = '';
        this.formObj.acceptor_pid = '';
        this.options['departments'] = [];
        this.setValidators();
    }
    nodeExpand(event) {
        if (event.node) {
            this.publicService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
                event.node.children  = res;
            });
        }
    }
    closeTreeDialog() {
        this.display = false;
        this.formObj.acceptor_org = this.selected['label'];
        this.formObj.acceptor_org_oid = this.selected['oid'];
        this.getDepPerson(this.selected['oid']);
    }
    getDepPerson(oid?) {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.options['departments'] = [];
            }else {
                let newArray = PUblicMethod.formateDepDropDown(res);
                this.options['departments'] = newArray;
                this.formObj.acceptor_pid = newArray[0]['value']['pid'];
                this.formObj.acceptor = newArray[0]['value']['name'];
            }
        });
    }
    onChange(event) {
        this.formObj.acceptor = event['value']['name'];
        this.formObj.acceptor_pid = event['value']['pid'];
    }
    submitTrick() {
        if ( !this.formObj.acceptor_org) {
            this.showError();
            this.setValidators();
        }else {
            this.formObj.status = '待接受';
            this.submitPost(this.formObj);
        }
    }
    get department() {
        return this.myForm.controls['department'].untouched && this.myForm.controls['department'].hasError('required');
    }
    setValidators() {
        this.myForm.controls['department'].setValidators([Validators.required]);
        this.myForm.controls['department'].updateValueAndValidity();
    }
    showError() {
        this.message = [];
        this.message.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
    }
    submitPost(paper) {
        this.rfsService.assignTrick( paper ).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
                window.setTimeout(() => {
                    this.router.navigateByUrl('/index/reqForService/rfsBase/serviceOverview');
                }, 1100);
            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
            }
        });
    }
}
